const net = require("net")
const path = require('path')
const fs = require("fs")
const fileTool = require('../tool/file')

let dataPath = path.join(__dirname, '../../data/')



module.exports = class TcpServer {
  onUpdate = (data) => { console.log(data) }
  obj = null

  transList = []

  static getInstant(){
    if (!this.obj) {
      this.obj = new TcpServer()
    }
    return this.obj
  }

  init() {
    console.log(this.onUpdate)
    const netServer = net.createServer(this.onConnect.bind(this));
    netServer.listen(9186, () => {
      console.log("running");
    });
  }

  onConnect(socket) {
    console.log(this.onUpdate)
    let buffer = Buffer.allocUnsafe(0)
    let transferBodyLength = 0
    let bodyLength = 0
    let fileName
    let step = 1
    let me = this
    socket.on("data", (data) => {
      if (step == 1) {
        getHeader(data)
      } else {
        getBody(data)
      }
    });
  
    socket.on("end", () => {
      console.log("bye bye ~");
    });


    function getHeader(data) {
      // 阶段1，获取头部，文件名
      buffer = Buffer.concat([buffer, data]);
        
      if (buffer.length < 14) {
        return
      }

      var nameBuffer = buffer.subarray(0, 6); //0-5 协议标志
      console.log(nameBuffer.toString())

      let nameLengthBuffer =  buffer.subarray(6, 10); //6-9 文件名长度
      let nameLength = nameLengthBuffer.readUInt32BE()
      console.log(nameLength)

      let dataLengthBuffer =  buffer.subarray(10, 14);//10-13 数据长度
      bodyLength = dataLengthBuffer.readUInt32BE()
      console.log(bodyLength)


      if (buffer.length < 14 + nameLength) {
        return
      }

      let fileNameBuffer = buffer.subarray(14, 14 + nameLength);//14 文件名  若nameLength=1
      fileName = fileNameBuffer.toString()
      console.log(fileName)

      if (buffer.length >  14 + nameLength) {
        getBody(buffer.subarray(14 + nameLength)) //15-xx 文件体  若nameLength=1
      }
    }

    let writerStream
    let beginTime
    let lastTime
    function getBody(data) {
      if (step == 1) {

        let filePath = dataPath + fileName
        if (fs.existsSync(filePath)) {
          fs.unlinkSync(filePath)
        }

        beginTime = new Date().getTime()
        lastTime = beginTime
        writerStream = fs.createWriteStream(filePath)
        writerStream.on('finish', function() {
          console.log("写入完成。");
        });

        me.transList.push({
          fileName: fileName
        })
        step = 2
      }
      transferBodyLength += data.length
  
      writerStream.write(data)

      if (transferBodyLength >= bodyLength) {
        writerStream.end()
        update(1)
      }

      let time = new Date().getTime()
      if (time - lastTime > 1000) { //间隔一秒更新进度状态
        lastTime = time
        update(0)
      }
      
    }

    function update(end) {
      let time = new Date().getTime()
      let allTime = Math.trunc((time - beginTime)/1000)
      let speed = '-'
      if (allTime > 0) {
        speed = fileTool.renderSize(Math.trunc(transferBodyLength/allTime))
      }

      for(var i = 0; i < me.transList.length; i++){
        if (me.transList[i].fileName == fileName){
          me.transList[i] = {
            allTime: allTime,
            transSize: fileTool.renderSize(transferBodyLength),
            speed,
            size: fileTool.renderSize(bodyLength),
            end:end,
            fileName: fileName
          }
          break
        }
      }
      me.onUpdate(me.transList)
    }
  }




}

